package sopt.engSearch;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;

import org.json.JSONException;
import org.json.JSONObject;

import statics.SoptVars;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.http.AccessToken;

import com.ibatis.sqlmap.client.SqlMapClient;

import comm.util.RequestManager;
import comm.util.SoptHashMap;
import comm.util.SqlMapLoader;

public class ESKoreaProc {
	private SqlMapClient sqlMapper = SqlMapLoader.getInstance();
	
	public ArrayList getSuggestList(String q){
		ArrayList lt = new ArrayList();
		
		try {
			lt = (ArrayList)sqlMapper.queryForList("suggest.getSuggestList",q);
		} catch (SQLException e) {
			e.printStackTrace();
			return lt;
		}
		
		return lt;
	}
	public String getKoreaSparklingWord(String q){
		String result = "";
		
		try {
			Object obj = sqlMapper.queryForObject("suggest.getKoreaSparklingWord",q);
			if(obj!=null)
				result = obj.toString();
		} catch (SQLException e) {
			e.printStackTrace();
			return result;
		}
		
		return result;
	}
	
	public SoptHashMap getMistakeWord(String q){
		SoptHashMap result = null;
		
		try {
			result = (SoptHashMap)sqlMapper.queryForObject("suggest.getMistakeWord",q);
		} catch (SQLException e) {
			e.printStackTrace();
			return result;
		}
		
		return result;
	}
	
	public boolean saveDiary(HttpServletRequest request) throws UnsupportedEncodingException{
		boolean result = false;
		
		SoptHashMap hm = RequestManager.getRequest(request);
		String shortUrl = "";
		hm.put("MEMBER_SEQ", request.getSession().getAttribute("MEMBER_SEQ").toString());
		
		try {
			String loungeSeq = sqlMapper.insert("forum.regDiary", hm).toString();
			
			if(hm.get("SHARE")!=null && hm.get("SHARE").toString().length()>0){
				shortUrl = getShortUrl(request, loungeSeq);
				
				System.out.println("드간다~ 포스트~");
				String twitResult = writeTwit(shortUrl,hm);
				System.out.println("나왔다~ 포스트~");
			}
			
			result = true;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return result;
	}
	
	public ArrayList getForumList(){
		ArrayList lt = null;
		try {
			lt = (ArrayList)sqlMapper.queryForList("forum.getForumList");
		} catch (SQLException e) {
			return lt;
		}
		return lt;
	}
	
	public SoptHashMap getForumBySeq(String seq){
		SoptHashMap hm = null;
		
		if(seq.length()<1)return null;
		
		try {
			hm = (SoptHashMap)sqlMapper.queryForObject("forum.getForumBySeq",seq);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return hm;
		}
		return hm;
	}
	
	public String getShortUrl(HttpServletRequest request, String seq){
		URL url = null;//URL 주소 객체
        URLConnection connection;//URL접속을 가지는 객체
        InputStream is;//URL접속에서 내용을 읽기위한 Stream
        InputStreamReader isr;
        BufferedReader br;
        String result = "";
        
        try{
            //URL객체를 생성하고 해당 URL로 접속한다..
            String requestStr = "http://ggl-shortener.appspot.com/?url="+ URLEncoder.encode("http://"+request.getServerName()+request.getContextPath()+"/engSearch/forumDirect.jsp?forum="+seq) + "&jsonp=googl_callback";
								
            url = new URL(requestStr);
            connection = url.openConnection();
            

            //내용을 읽어오기위한 InputStream객체를 생성한다..
            is = connection.getInputStream();
            
            
            isr = new InputStreamReader(is,"UTF-8");
            br = new BufferedReader(isr);
            
            //내용을 읽어서 화면에 출력한다..
            String buf = null;
            result = "";
            while(true){
                buf = br.readLine();
                if(buf!=null)result+=buf;
                else break;
                
                //System.out.println(buf);
            }
        }catch(MalformedURLException mue){
            System.err.println("잘못되 URL입니다. 사용법 : java URLConn http://hostname/path]");
            System.exit(1);
        }catch(IOException ioe){
            System.err.println("IOException " + ioe);
            ioe.printStackTrace();
            System.exit(1);
        }
        
        JSONObject jsonObject;
		try {
			jsonObject = new JSONObject(result.substring(result.indexOf("{"), result.lastIndexOf("}")+1));
			
			result = jsonObject.getString("short_url");
	        
		} catch (JSONException e) {
			
		}
		System.out.println("======줄여진 주소:"+result);
		return result;
	}
	
	public String writeTwit(String shortUrl, SoptHashMap hm) throws SQLException{
		String result = "ERROR";
		try {
			
			Twitter twitter = new Twitter();
			
			twitter.setOAuthConsumer(SoptVars.twitterConsumerKey, SoptVars.twitterConsumersecret);
			
			
			String tokenPare = sqlMapper.queryForObject("forum.getMemberPasskeyBySeq",hm.get("MEMBER_SEQ")).toString();
			
			System.out.println("아싸 받아냈다~~"+tokenPare);
			String accessToken = tokenPare.substring(0, tokenPare.indexOf("@"));
			String accessTokenSecret = tokenPare.substring(tokenPare.indexOf("@")+1);
			AccessToken at = new AccessToken(accessToken,accessTokenSecret);
			twitter.setOAuthAccessToken(at);
		
			
			String content = hm.get("TITLE").toString();
			String return_url = shortUrl;
						
			content = content.length() >= 120 ? content.substring(0, 119) : content;
			content = content + " from" + return_url;
			twitter.updateStatus(content).getText();
			
			if(result.equals(content)){
				result = SoptVars.SUCCESS;
			}
			System.out.println("@@@@@@@@@@트위터 포스팅 결과:@@@@"+result);

		}  catch (TwitterException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}
}
